<?php
/**
 * 积分商城
 */
namespace Common\Model;
use Think\Exception;

class PointMallModel extends BaseModel{
	static $instance=null;
	private function getInstance(){
		if(!self::$instance){
			self::$instance=M('point_mall',null,DB_MAIN_CFG);
		}
		return self::$instance;
	}

	//积分商城 库存真实状态
	const POINTMALL_NO_LIMIT	=-1;//没有库存限制
	const POINTMALL_NO_STACK	=0;//缺货
	const POINTMALL_NO_LIMIT_QUOTA=0;//不限购

	//库存查询状态枚举
	const STOCK_DEFAULT 	= 0;//不限库存状况
	const STOCK_LACK 		= 1;//缺货
	const STOCK_AMPLE 		= 2;//库存充足

	//订单过期时间，超5分钟未完成订单，则订单过期
	const ORDER_EXPIRE_TIME_SELF =600;//10分钟   相对主体的过期时间
	const ORDER_EXPIRE_TIME_OTHER =660;//11分钟  其它人参与过期时间

	//时间相关
	const TIME_ALL		=0;//全部
	const TIME_ONLNE	=1;//进行中
	const TIME_BEFORE	=2;//开始之前
	const TIME_AFTER	=3;//截止时间之后
	const TIME_ONLINE_AND_PAST=4;//进行中及往期的
	const TIME_ONLINE_AND_PREPARE=5;//进行中及待上线


	//管理员控制位，上线状态
	const POINTMALL_IS_ONLINE  =1;//已经上线
	const POINTMALL_IS_PREPARE =2;//未上线


	//兑换发放类型
	const DELIVERY_ALL			=0; //全部
	const DELIVERY_SEND			= 1;//快递发货
	const DELIVERY_CARD			= 2;//凭电子券,如商家启用我们的核销系统，则使用
	const DELIVERY_TRAFFIC		= 3;//流量红包 废弃
	const DELIVERY_PHONE		= 4;//凭手机号,
	/**
	 * 获取配送形式
	 * Author: shijy
	 * @return array
	 */
	public static function getDeliveryType(){
		return array(
			self::DELIVERY_SEND 	=> '需发货',
			self::DELIVERY_CARD 	=> '凭电子券核销',
			self::DELIVERY_PHONE 	=> '凭手机号核销',
//			self::DELIVERY_TRAFFIC => '流量红包'//作废
		);
	}

	//用户活动交互状态
	const EXCHANGE_EVENT_JOINED		=1;//已抢兑
	const EXCHANGE_EVENT_GOJOIN		=2;//去抢兑
	const EXCHANGE_EVENT_WAITING	=3;//未开始
	const EXCHANGE_EVENT_END		=4;//已结束


	//兑换完成状态
	const EXCHANGE_STATUS_UNCOMPLETE	= 0;//未完成信息填写
	const EXCHANGE_STATUS_SUCCESS		= 1;//完成
	const EXCHANGE_STATUS_ERROR			= 2;//异常错误的订单
	const EXCHANGE_STATUS_UNPAY			= 3;//未完成支付

	//需发货的提货方式
	const DELIVERY_SEND_PICK		=1;//自提
	const DELIVERY_SEND_EXPRESS		=2;//快递

	public static function getExchangeStatus(){
		return array(
			self::EXCHANGE_STATUS_UNCOMPLETE=>'未完成订单',
	 		self::EXCHANGE_STATUS_SUCCESS=>'成功订单',
	 		self::EXCHANGE_STATUS_ERROR=>'错误订单',
			self::EXCHANGE_STATUS_UNPAY	=>'未支付'
		);
	}




	
	/**
	 * 返回用户参加次数
	 * Author: shijy
	 * @param $uid
	 * @param $pointMallId
	 * @return mixed
	 */
	public static function getUserJoinTimes($pointMallId,$uid=0){
		return M('exchange_log',null,DB_MAIN_CFG)->where("uid={$uid} and pid={$pointMallId}")->count();
	}


	/**
	 * 根据类型获取全部积分活动
	 * Author: shijy
	 * @param $actionType
	 * @param $count
	 * @return array
	 */
	public static function getByActionType($actionType,$count,$clientShow=CLIENT_SHOW_ALL,$uid=0){
		return self::getList(self::POINTMALL_IS_ONLINE,$actionType,1,$count,self::TIME_ALL,self::STOCK_DEFAULT,$clientShow,$uid);
	}


	/**
	 * 获取积分商城商品分类
	 * @return mixed
	 */
	public static function getGoodsType(){
		return M("cfg_goods_type",null,DB_MAIN_CFG)->order("showOrder desc")->getField("id,showName");
	}



	/**
	 * 获取指定条数的已上线，且时间处于进行中的积分商城活动
	 * Author: shijy
	 * @param $actionType 活动类型
	 * @param $count 数量
	 * @param int $clientShow 展现平台
	 * @return array
	 */
	public static function getOnlineTop($count,$clientShow=CLIENT_SHOW_ALL,$uid=0){
		return self::getList(self::POINTMALL_IS_ONLINE,1,$count,self::TIME_ONLNE,self::STOCK_DEFAULT,$clientShow,$uid);
	}



	/**
	 *正在进行中，及即将上线的
	 * Author: shijy
	 * @param $actionType
	 * @param $page
	 * @param $pageSize
	 * @param int $clientShow
	 * @return array
	 */
	public static function getOnlineAndPrepareList($page,$pageSize,$clientShow=CLIENT_SHOW_ALL,$uid=0){
		return self::getList(self::POINTMALL_IS_ONLINE,$page,$pageSize,self::TIME_ONLINE_AND_PREPARE,self::STOCK_DEFAULT,$clientShow,$uid);
	}

	/**
	 * 获取列表数据的基础方法
	 * Author: shijy
	 * @param $onlineStatus
	 * @param $actionType
	 * @param $page
	 * @param $pageSize
	 * @param int $timeSwitch 时间要求
	 * @param $stockSwitch 库存
	 * @param int $clientShow 展现渠道
	 * @return array
	 */
	public static function getList($onlineStatus,$page,$pageSize,$timeSwitch=0,$stockSwitch,$clientShow=CLIENT_SHOW_ALL,$uid=0){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		$now_time=time();
		$pointMall = self::getInstance();

		$where="`status`={$onlineStatus}";

		if($onlineStatus==self::POINTMALL_IS_ONLINE){
			$where .=" and status =".self::POINTMALL_IS_ONLINE;
		}

		if($clientShow!=CLIENT_SHOW_ALL){
			$where .=" and find_in_set({$clientShow},clientShow)";
		}


		//库存状态
		switch($stockSwitch){
			case self::STOCK_AMPLE://充足
				$where.=' and (stock=0 or stock>buyNum)';
				break;
			case self::STOCK_LACK://缺货
				$where.=' and buyNum>=stock and stock>0';
				break;
			default:
				break;
		}

		$field='*';
		$showOrder='showOrder desc';
		//时间要求
		switch($timeSwitch){
			case self::TIME_BEFORE://未开始
				$where.=" and beginShowTimestamp > {$now_time} ";
				break;
			case self::TIME_ONLNE://进行中
				$where.=" and  {$now_time} between beginShowTimestamp and endExchangeTimestamp";
				break;
			case self::TIME_AFTER://结束时间之后
				$where.=" and endExchangeTimestamp <{$now_time} ";
				$showOrder='endExchangeTimestamp desc';
				break;
			case self::TIME_ONLINE_AND_PAST://进行中及往期
				$where.=" and beginExchangeTimestamp <{$now_time} ";
				$field="*,case when beginShowTimestamp>{$now_time} then 2 when beginShowTimestamp<{$now_time} and endExchangeTimestamp>{$now_time} then 1 when endExchangeTimestamp<{$now_time} then 3 end  as onlineStatus";
				$showOrder="onlineStatus asc,if(onlineStatus=3,endExchangeTimestamp,showOrder) desc";
				break;
			case self::TIME_ONLINE_AND_PREPARE://进行中及待上线
				$where.=" and endExchangeTimestamp > {$now_time} and {$now_time} > beginShowTimestamp";
				$field="*,case when beginExchangeTimestamp>{$now_time} then 1 when beginExchangeTimestamp<{$now_time} and endExchangeTimestamp>{$now_time} then 2 when endExchangeTimestamp<{$now_time} then 3 end  as onlineStatus";
				//$showOrder="onlineStatus DESC,showOrder desc";
				break;
			default://其它显示全部
				$field="*,case when beginShowTimestamp>{$now_time} then 1 when beginShowTimestamp<{$now_time} and endExchangeTimestamp>{$now_time} then 2 when endExchangeTimestamp<{$now_time} then 3 end  as onlineStatus";
				$showOrder="onlineStatus asc,if(onlineStatus=3,endExchangeTimestamp,showOrder) desc";
				break;
		}



		$dataSuccess['total'] = $pointMall->where($where)->count();//获取数据总条数
		$dataSuccess['page'] = $page ? $page : 1;//返回当前页
		$dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
		$dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
		$offset=($dataSuccess['page']-1)*$pageSize;


		$exchangeList = $pointMall->where($where)
			->field($field)
			->order($showOrder)
			->limit($offset,$pageSize)
			->select();


		//兑换类型列表
		foreach($exchangeList as $key => $value){
			if($now_time < $value['beginExchangeTimestamp']) {
				$exchangeList[$key]['restTime'] = ($value['beginExchangeTimestamp']-$now_time);
			}else{
				$exchangeList[$key]['restTime'] = 0;
			}
			if($value['endExchangeTimestamp'] < $now_time){
				$exchangeList[$key]['overdue'] = true;
			}else{
				$exchangeList[$key]['overdue'] = false;
			}

			//标志活动状态
			if($now_time < $value['beginExchangeTimestamp']){
				$exchangeList[$key]['showStatus'] = self::EXCHANGE_EVENT_WAITING;
			} elseif ($value['endExchangeTimestamp'] < $now_time){
				$exchangeList[$key]['showStatus'] = self::EXCHANGE_EVENT_END;
			} else{
				$exchangeList[$key]['showStatus'] = self::EXCHANGE_EVENT_GOJOIN;
			}

			$stock=self::tempStock($value['id']);
			$exchangeList[$key]['salesVolume']=$stock['buyNum'];//实销+调节
			$exchangeList[$key]['showStock']=$stock['showStock'];


			if($exchangeList[$key]['showStock'] <= 0){
				$exchangeList[$key]['showStock'] = 0;
			}

			//价格显示取整
			$exchangeList[$key]['originalPrice'] = $value['originalPrice'];
		}


		$dataSuccess['data']=$exchangeList;
		return $dataSuccess;
	}





	public static function getListByGoodsType($goodsType,$page,$pageSize){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$now_time=time();
		$pointMall = self::getInstance();

		$where="status =".self::POINTMALL_IS_ONLINE;

		if($goodsType!=CLIENT_SHOW_ALL){
			$where .=" and find_in_set({$goodsType},goodsType)";
		}

		$field='*';
		$showOrder='(stock=0 or stock>buyNum) desc,showOrder desc';
		$where.=" and {$now_time} between beginShowTimestamp and endExchangeTimestamp";


		$dataSuccess['total'] = $pointMall->where($where)->count();//获取数据总条数
		$dataSuccess['page'] = $page ? $page : 1;//返回当前页
		$dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
		$dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
		$offset=($dataSuccess['page']-1)*$pageSize;


		$exchangeList = $pointMall->where($where)
			->field($field)
			->order($showOrder)
			->limit($offset,$pageSize)
			->select();


		//兑换类型列表
		foreach($exchangeList as $key => $value){
			if($now_time < $value['beginExchangeTimestamp']) {
				$exchangeList[$key]['restTime'] = ($value['beginExchangeTimestamp']-$now_time);
			}else{
				$exchangeList[$key]['restTime'] = 0;
			}
			if($value['endExchangeTimestamp'] < $now_time){
				$exchangeList[$key]['overdue'] = true;
			}else{
				$exchangeList[$key]['overdue'] = false;
			}

			//标志活动状态
			if($now_time < $value['beginExchangeTimestamp']){
				$exchangeList[$key]['showStatus'] = self::EXCHANGE_EVENT_WAITING;
			} elseif ($value['endExchangeTimestamp'] < $now_time){
				$exchangeList[$key]['showStatus'] = self::EXCHANGE_EVENT_END;
			} else{
				$exchangeList[$key]['showStatus'] = self::EXCHANGE_EVENT_GOJOIN;
			}

			$stock=self::tempStock($value['id']);
			$exchangeList[$key]['salesVolume']=$stock['buyNum'];//实销+调节
			$exchangeList[$key]['showStock']=$stock['showStock'];


			if($exchangeList[$key]['showStock'] <= 0){
				$exchangeList[$key]['showStock'] = 0;
			}

			//价格显示取整
			$exchangeList[$key]['originalPrice'] = $value['originalPrice'];
		}


		$dataSuccess['data']=$exchangeList;
		return $dataSuccess;
	}

	/**
	 * 返回专区数据
	 * Author: shijy
	 * @param $actionType
	 * @param int $clientShow
	 * @return array[在线及待上线，往期]
	 */
	public static function getSpecialArea($actionType,$clientShow=CLIENT_SHOW_ALL,$uid){
		$mReturn=self::getOnlineAndPrepareList($actionType,1,10,$clientShow,$uid);
		$listO = $mReturn['data'];
		$mReturn=self::getPastList($actionType,1,2,$clientShow,$uid);

		$listP = $mReturn['data'];
		return array($listO,$listP);
	}



	/**
	 * 返回专区数据--web
	 * Author: shijy
	 * @param $actionType
	 * @param $page
	 * @param $pageSize
	 * @param int $clientShow
	 * @return array
	 */
	public static function getSpecialAreaList($actionType,$page,$pageSize,$clientShow=CLIENT_SHOW_ALL,$uid=0){
		return self::getList(self::POINTMALL_IS_ONLINE,$actionType,$page,$pageSize,self::TIME_ALL,self::STOCK_DEFAULT,$clientShow,$uid);
	}


	/**
	 * 获取积分商城活动详情
	 * Author: shijy
	 * @param $id
	 * @return array
	 */
	public static function getDetail($id,$from=null){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		if(!$id){
			return $dataFailure;
		}
		$detail=null;//S('pointMall_'.$id);
		if(!$detail) {
			$detail = self::getInstance()->where("id={$id}")->find();
			if($detail){
				S('pointMall_'.$id,$detail);
			}
		}
		if(!$detail){
			$dataFailure['msg']='指定活动不存在';
			return $dataFailure;
		}

		if($from=="article_detail"){	//文章详情页关联积分商城信息
//			$detail['cover'] = substr($detail['cover'],0,30)."210142/".substr($detail['cover'],37);
			$detail['cover'] = substr($detail['cover'],0,42)."210142/".substr($detail['cover'],49);
		} else{
			$stock=self::tempStock($id);
			$detail['stock']=$stock['stock'];
			$detail['buyNum']=$stock['buyNum'];
			$detail['showStock']=$stock['showStock'];
			$detail['unComplete']=$stock['unComplete'];

			$detail['views']=self::views($id);
		}

		$dataSuccess['data']=$detail;
		return $dataSuccess;
	}

	/**
	 * 临时库存,在时效内未完成的订单计入已购买
	 * Author: shijy
	 * @param $pointMallId
	 * @return mixed
	 */
	public static function tempStock($pointMallId){
		$stock=self::stock($pointMallId);
		$now=time();
		//库存判断2
		$expireTime=$now-self::ORDER_EXPIRE_TIME_OTHER;//小于该时间的订单失效
		//获取用户是否存在没有提交信息的兑换
		$where="pid={$pointMallId} and status in (".self::EXCHANGE_STATUS_UNCOMPLETE.','.self::EXCHANGE_STATUS_UNPAY.') and exchangeTime>'.$expireTime;
		$unComplete = M('exchange_log',null,DB_MAIN_CFG)->where($where)->count();
		$stock['buyNum']	= $stock['buyNum']+$stock['soldAdjust'] + $unComplete;//购买数量+调剂数量+未完成数量
		$stock['showStock'] = $stock['stock']==self::POINTMALL_NO_LIMIT?self::POINTMALL_NO_LIMIT:$stock['stock']-$stock['buyNum'];//显示库存量
		if($stock['showStock']<0){
			$stock['showStock']=0;
		}
		$stock['unComplete']= $unComplete;
		return $stock;
	}

	/**
	 * 数据库永久库存
	 * Author: shijy
	 * @param $id
	 * @param null $changeVal
	 * @return mixed
	 */
	private static function stock($id,$changeVal=null){
		if(is_null($changeVal)){//读
			$stock=self::getInstance()->where("id={$id}")->field('stock,buyNum,soldAdjust')->find();
			return $stock;
		}else{//写
			self::getInstance()->where("id={$id}")->save($changeVal);
		}
	}




	//读取指定活动的展现量
	public static function views($id,$add=null,$uid=0,$contentType=0){
		if(is_null($add)){//读
			$views=S('pointMallViews_'.$id);
			if(!$views){
				$views=S('pointMall_'.$id);
				return $views['$views'];
			}else{
				return $views;
			}
		}else{//写
			$pointMall=self::getInstance();
			$views=1+$pointMall->where("id={$id}")->getField('views');
			$pointMall->where("id={$id}")->setInc('views');
			S('pointMallViews_'.$id,$views);

		}

	}

	/**
	 * 获取活动参与者列表
	 * Author: shijy
	 * @param $id
	 * @param $page
	 * @param $pageSize
	 * @return array
	 */
	public static function getMemberList($id,$page,$pageSize){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		if(!$id || $id<1){
			$dataFailure['msg']='请指定正确的积分商城活动';
			return $dataFailure;
		}


		$M = M('exchange_log',null,DB_MAIN_CFG);

		$where="pid={$id} and status=".self::EXCHANGE_STATUS_SUCCESS;

		$dataSuccess['total'] = $M->where($where)->count();//获取数据总条数
		$dataSuccess['page'] = max($page , 1);//返回当前页
		$dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
		$dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
		$offset=($dataSuccess['page']-1)*$pageSize;
		$list = $M->where($where)
			->order('exchangeTime desc')
			->limit($offset,$pageSize)
			->select();
		$dataSuccess['data']=$list;
		return $dataSuccess;
	}


	/**
	 * 获取兑换日志列表
	 * Author: shijy
	 * @param $uid
	 * @param $page
	 * @param $pageSize
	 * @return array
	 */
	public static function getExchangeLogList($uid,$page,$pageSize){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		//$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$exchangeLog = M('exchangeLog',null,DB_MAIN_CFG);//兑换记录表
		$where='uid='.$uid;
		$dataSuccess['total'] = $exchangeLog->where($where)->count();//获取数据总条数
		$dataSuccess['page'] = max($page , 1);//返回当前页
		$dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
		$dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
		$offset=($dataSuccess['page']-1)*$pageSize;

		$list = $exchangeLog
			->field('point_mall.id,point_mall.titleList,point_mall.point,
            point_mall.originalPrice,point_mall.nowPrice,point_mall.listPic,exchange_log.exchangeTime,exchange_log.status')
			->join('point_mall on exchange_log.pid = point_mall.id')
			->where($where)
			->order('exchange_log.exchangeTime desc')
			->limit($offset,$pageSize)
			->select();

		$dataSuccess['data']=$list;
		return $dataSuccess;
	}

	/**
	 * 增加卡券兑换日志
	 * Author: shijy
	 * @param $uid
	 * @param $nickname
	 * @param $pointMallId
	 * @param $cardNum
	 * @param $point
	 * @param int $cash
	 * @param int $status
	 */
	public static function addCardExchangeLog($uid,$nickname,$pointMallId,$contentType,$cardNum,$point,$cash=0,$status=self::EXCHANGE_STATUS_SUCCESS,$payOrderNo=0){
		//存入基本信息
		$record_data = array(
			'uid' 			=> $uid,
			'nickname' 		=> $nickname,
			'pid' 			=> $pointMallId,
			'objContentType'=> $contentType,
			'cardNum' 		=> $cardNum,
			'costCash' 		=> $cash,
			'costPoint' 	=> $point,
			'status' 		=> $status,
			'payOrderNo'	=> $payOrderNo,
			'exchangeTime' 	=> time()
		);

		$userinfo=UserModel::getUser($uid);
		$record_data['realName'] = $userinfo['data']['realName'];
		$record_data['phone'] = $userinfo['data']['bindPhone'];
		unset($userinfo);

		//存入兑换记录
		$exchangeLog = M('exchange_log',null,DB_MAIN_CFG);//兑换记录表
		$exchangeLog->add($record_data);
	}


	/**
	 * 验证活动跳转过来的优惠是否成立
	 * Author: shijy
	 * @param $pointMallId
	 * @param $uid
	 * @param $eventID
	 * @return array
	 */
	public static function validateEvent($pointMallId,$uid,$eventID)
	{
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$where="id={$eventID} and relation='point_mall' and relationId={$pointMallId}";
		$event=M('e_events',null,DB_MAIN_CFG)->where($where)->field('discount')->find();
		if(!$event || $event['discount'] <= 0){
			$dataFailure['msg'] = '并没有活动支持本次优惠';
			return $dataFailure;
		}


		$where="uid={$uid} and eid={$eventID}";
		$uEvent=$eventJoin=M('e_events_join',null,DB_MAIN_CFG)
			->where($where)
			->field('status,pointMallTime')
			->find();
		if(!$uEvent){
			$dataFailure['msg'] = '你尚未参加活动';
			return $dataFailure;
		}
		if($uEvent['status']!=EventsModel::JOIN_STATUS_UNSELECTED ){
			$dataFailure['msg'] = '只有未入选活动才可享受本优惠';
			return $dataFailure;
		}

		if($uEvent['pointMallTime'] >0) {
			$dataFailure['msg'] = '您已享受过本优惠，不可重复享受！';
			return $dataFailure;
		}
		$dataSuccess['discount']=$event['discount'];
		return $dataSuccess;
	}


	/**
	 * 检测是否可以兑换
	 * Author  shijy
	 * @param $pointMallId
	 * @param $uid
	 * @param $userLevel
	 * @param int $eventID 对应的活动编号
	 * @return array
	 */
	public static function validateExchange($pointMallId,$uid,$userLevel,$eventID=0){
		$dataSuccess 	= array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure 	= array('status'=>self::FAILURE,'msg'=>'无效参数');

		//模型 start
		$user_base 		= M('u_user_base',null,DB_MAIN_CFG);//用户表
		$exchangeLog 	= M('exchange_log',null,DB_MAIN_CFG);//兑换记录表
		//模型 end

		//获取缓存
		$mReturn = self::getDetail($pointMallId);//S('pointMallItem'.$id);

		if($mReturn['status']==0){
			$pointMallItem = $mReturn['data'];
		}else{
			$pointMallItem = null;
		}

		//获取用户信息
		$mReturn=UserModel::getUser($uid);
		if($mReturn['status']==0 ){
			$userinfo=$mReturn['data'];
		}else{
			$userinfo=null;
		}

		$now=time();
		//活动还没开始
		if($pointMallItem['beginExchangeTimestamp'] > $now){
			$dataFailure['msg'] = '活动还没有开始';
			return $dataFailure;
		}
		//活动已经结束了
		if($pointMallItem['endExchangeTimestamp'] < $now){
			$dataFailure['msg'] = '活动已经结束';
			return $dataFailure;
		}


		if($pointMallItem['mustFollow']==1){
			if(!UserModel::checkFollow($uid)){
				$data = array('status'=>2, 'msg'=>'本次活动要求您必须关注本公众号才可参与');//要求关注
				return $data;
			}
		}



		//会员等级不够
		if($pointMallItem['userLevelRequire'] > $userLevel){
			$dataFailure['msg'] = '您的会员等级未达到，无法购买';
			return $dataFailure;
		}



		//从活动中跳转过来的。
		$discount=0;
		if($eventID){
			$rt=self::validateEvent($pointMallId, $uid, $eventID);
			if($rt['status']!=0) {
				return $rt;
			}
			$discount=$rt['discount'];
		}
		$needPoint=$discount>0?ceil($pointMallItem['point'] * $discount):$pointMallItem['point'];

		//积分不够
		if($needPoint > $userinfo['point']){
			$dataFailure['status'] = 99;
			$dataFailure['msg'] = '您的积分不够，不能参加活动';
			return $dataFailure;
		}


		$stockObj=self::tempStock($pointMallId);
		//库存已经被抢完
		if($stockObj['stock']!=self::POINTMALL_NO_LIMIT &&  $stockObj['stock'] <= $stockObj['buyNum']){
			if( $stockObj['unComplete'] > 0 ) {
				$dataFailure['msg'] = '尚有用户未完成订单，如其放弃还可抢单唷';
				return $dataFailure;
			}
			$dataFailure['msg'] = '该活动已经被抢完';
			return $dataFailure;
		}


		if($pointMallItem['quota'] != self::POINTMALL_NO_LIMIT_QUOTA){
			//获取用户已购买的数量
			$recordCount = $exchangeLog->where('uid=' . $uid . ' and pid=' . $pointMallItem['id'].' and status='.PointMallModel::EXCHANGE_STATUS_SUCCESS)->count();
			//超过购买的限额
			if($recordCount >= $pointMallItem['quota'] ){
				$dataFailure['msg'] = '您已经超过限购次数';
				return $dataFailure;
			}
		}
		return $dataSuccess;
	}

	/**
	 * 根据积分商城活动的配置，获取卡券的有效期,仅为本平台专属卡券时有效，微信卡券不能使用
	 * Author: shijy
	 * @param $pointMallItem
	 * @return array{
	 *    beginTimestamp 开始时间戳;
	 *    endTimestamp 结束时间戳
	 * }
	 */
	private static function getCardExpiresWithPointMall(&$pointMallItem){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		//绝对时间
		if($pointMallItem['cardFixBeginTime']>0 && $pointMallItem['cardFixEndTime']>0){
			$beginTimestamp	= $pointMallItem['cardFixBeginTime'];
			$endTimestamp	= $pointMallItem['cardFixEndTime'];
		}elseif($pointMallItem['cardFixedTerm']>0){
			$beginTimestamp=strtotime('today');
			if($pointMallItem['cardfixedBeginTerm']>=1){//当天
				$beginTimestamp +=UtilsModel::ONE_DAY * $pointMallItem['cardfixedBeginTerm'];
			}
			$endTimestamp	= $beginTimestamp +UtilsModel::ONE_DAY * $pointMallItem['cardFixedTerm'];
		}else{
			$dataFailure['msg']='卡券的有效期不正确';
			return $dataFailure;
		}

		$dataSuccess['beginTimestamp']	= $beginTimestamp;
		$dataSuccess['endTimestamp']	= $endTimestamp;
		return $dataSuccess;
	}


	/**
	 * 支付后的回调整操作
	 * Author: shijy
	 * @param null $payOrderNo
	 * @return array
	 */
	public static function afterPay($payOrderNo=null,$payStatus=0,$uid,$objID){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		if($payStatus!=0){
			$dataFailure['msg']='支付失败';
			return $dataFailure;
		}

		if(!$payOrderNo){
			$dataFailure['msg']='支付单号不能为空！';
			return $dataFailure;
		}

		$exchangeLogM=M('exchange_log',null,DB_MAIN_CFG);
		$log=$exchangeLogM->where('payOrderNo='.$payOrderNo)->find();
		if(!$log){
			$dataFailure['msg']='找不到对应的兑换记录';
			return $dataFailure;
		}

		if($log['status']!=PointMallModel::EXCHANGE_STATUS_UNPAY){
			$dataFailure['msg']='兑换记录状态异常';
			return $dataFailure;
		}
		$pointMallItem=self::getInstance()->where("id={$log['pid']}")->find();
		if($log['selectedWay']==self::DELIVERY_CARD){
			$sendCard= self::finishCardExchange($log['uid'],$pointMallItem);
			if($sendCard['status']!=0){
				$exchangeLogM->where('payOrderNo='.$payOrderNo)->setField('status',PointMallModel::EXCHANGE_STATUS_ERROR);
			}else{
				$exchangeLogM->where('payOrderNo='.$payOrderNo)->setField('status',PointMallModel::EXCHANGE_STATUS_SUCCESS);
				self::sendTemplateMsg($log['pid'],$log['nickname'],$log['phone']);
			}
			return $sendCard;
		}else{
			$exchangeLogM->where('payOrderNo='.$payOrderNo)->setField('status',PointMallModel::EXCHANGE_STATUS_SUCCESS);
			self::sendTemplateMsg($log['pid'],$log['nickname'],$log['phone']);
		}
		return $dataSuccess;
	}


	/**
	 * 完成卡券最终发送到用户
	 * Author: shijy
	 * @param $uid 用户编号
	 * @param $pointMallItem 兑换活动详情
	 * @return array
	 * @throws Exception
	 */
	private function finishCardExchange($uid,&$pointMallItem){
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		$baseCardInfo=CouponModel::getCardBaseInfo($pointMallItem['cardId']);
		if($baseCardInfo['status']!=0){
			return $baseCardInfo;
		}

		//根据平台开关，确定是哪类卡券发送
		switch($baseCardInfo['data']['platformSwitch']+0){
			case CouponModel::CARD_PLATFORM_WEIXIN://纯微信
				throw new Exception("纯微信卡券功能尚未实现");
				break;
			case CouponModel::CARD_PLATFORM_BOTH://平台微信打通
				$result= CouponModel::sendCard_both($pointMallItem['cardId'],$uid,OBJ_TYPE_POINTMALL,$pointMallItem['id']);
				$result['isWeixinCard']=1;
				break;
			case CouponModel::CARD_PLATFORM_STARJOY://仅平台
				//通过积分兑换活动确定卡券有效期
				//$expires=self::getCardExpiresWithPointMall($pointMallItem);
				//if($expires['status']!=0){
				//	return $expires;
				//}
				//return CouponModel::sendCard_starjoy($pointMallItem['cardId'],$uid,$expires['beginTimestamp'],$expires['endTimestamp']);
				$result= CouponModel::sendCard_starjoy($pointMallItem['cardId'],$uid);
				$result['isWeixinCard']=0;
				break;
			default:
				$dataFailure['msg'] = '错误的类型';
				$result = $dataFailure;
		}
		return $result;
	}


	/**
	 * 非卡券类直接兑换
	 * Author: shijy
	 * @param $pointMallId
	 * @param $uid
	 * @param $nickname
	 * @param $phone
	 * @param $realName
	 * @param string $address
	 * @param int $eventID 活动编号
	 * @param int $userlevel 用户等级
	 * @return array
	 */
	public static function doExchange($pointMallId,$uid,$nickname,$phone,$realName,$address=null,$eventID=0,$selectedWay=0,$userlevel=0){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		//模型 start
		$exchangeLog = M('exchange_log',null,DB_MAIN_CFG);//兑换记录表
		//模型 end

		//获取缓存
		$pmReturn=self::getDetail($pointMallId);
		if($pmReturn['status']==0){
			$pointMallItem = $pmReturn['data'];
			$deliveryTypeOptions=explode(',',$pointMallItem['deliveryType']);
			if(!in_array($selectedWay,$deliveryTypeOptions)){
				$dataFailure['msg']="没有指定的消费方式！";
				return $dataFailure;
			}
		}else{
			$dataFailure['msg']="没有指定的积分商品";
			return $dataFailure;
		}

		switch ($selectedWay){
			case PointMallModel::DELIVERY_CARD:
				break;
			case PointMallModel::DELIVERY_PHONE:
				if(!filedPreMatch('phone', $phone)){
					$dataFailure['msg'] = '手机号码格式错误';
					return $dataFailure;
				}
				break;
			case PointMallModel::DELIVERY_SEND:
				if(!filedPreMatch('phone', $phone)){
					$dataFailure['msg'] = '手机号码格式错误';
					return $dataFailure;
				}
				if(!$realName){
					$dataFailure['msg'] = '请输入您的真实姓名';
					return $dataFailure;
				} else if(strlen($realName)<2 || strlen($realName)>18){
					$dataFailure['msg'] = '真实姓名格式错误';
					return $dataFailure;
				}
				if (!$address) {
					$dataFailure['msg'] = '请填写收货地址';
					return $dataFailure;
				}
				break;
			default:
				$dataFailure['msg']="消费方式错误";
				return $dataFailure;
				break;
		}





		//从活动中跳转过来的。
		$discount=0;
		if($eventID){
			$rt=self::validateEvent($pointMallId, $uid, $eventID);
			if($rt['status']!=0) {
				return $rt;
			}
			$discount=$rt['discount'];
		}
		$needPoint	= $discount>0?ceil($pointMallItem['point'] * $discount):$pointMallItem['point'];
		$needMoney	= $discount>0?ceil($pointMallItem['nowPrice'] * $discount):$pointMallItem['nowPrice'];
		$deliveryFee= $pointMallItem['deliverPay'];
		if ($selectedWay==PointMallModel::DELIVERY_SEND && $deliveryFee>0){
			$needMoney+=$deliveryFee;
		}


		$validateResult=self::validateExchange($pointMallId,$uid,$userlevel,$eventID);
		if($validateResult['status']!=0){
			return $validateResult;
		}





		//存入基本信息
		$record_data = array(
			'uid' 			=> $uid,
			'nickname' 		=> $nickname,
			'pid' 			=> $pointMallId,
			'objContentType'=> $pointMallItem['contentType'],
			'costCash' 		=> $needMoney,
			'costPoint' 	=> $needPoint,
			'status' 		=> PointMallModel::EXCHANGE_STATUS_SUCCESS,
			'exchangeTime' 	=> time(),
			'phone'    		=> $phone,
			'realName' 		=> $realName,
			'selectedWay'	=> $selectedWay
		);

		//判断是否填写地址
		if($selectedWay == self::DELIVERY_SEND) {
			$record_data['address'] = $address;
		}

		$stockObj=self::tempStock($pointMallId);
		if($stockObj['stock']!=self::POINTMALL_NO_LIMIT &&  $stockObj['stock'] <= $stockObj['buyNum']){
			$dataFailure['msg'] = '库存不足！';
			return $dataFailure;
		}

		if($needMoney>0) {
			//兑换日志
			$data=array(
				'uid'			=> $uid,
				'objType'		=> OBJ_TYPE_POINTMALL,
				'objID'			=> $pointMallId,
				'orderTitle'	=> $pointMallItem['titleList'],
				'orderDesc'		=> $pointMallItem['titleInner'],
				'point'			=> $needPoint,
				'pay'			=> $needMoney,
				'marketPrice'	=> floatval($pointMallItem['originalPrice']),
				'userName'		=> '',
				'address'		=> '',
				'phone'			=> ''
			);
			$payOrderNo=OrderModel::buildOrder($data);
			$record_data['status']		= PointMallModel::EXCHANGE_STATUS_UNPAY;
			$record_data['payOrderNo']	= $payOrderNo;
			//删除同活动下未支付之订单
			$exchangeLog->where('uid=' . $uid . ' and pid=' . $pointMallId.' and status='.PointMallModel::EXCHANGE_STATUS_UNPAY)->delete();
			$exchangeLog->add($record_data);

			$dataSuccess['orderStatus']=PointMallModel::EXCHANGE_STATUS_UNPAY;
			$dataSuccess['jumpUrl']='./pay/paycenter.php?m=PayCenter&c=Order&a=pay&id='.$payOrderNo;
			return $dataSuccess;
		}
		else{
			UserModel::getInstance()->startTrans();
			$tmpR=UserModel::minusPoint($uid,-1,$needPoint,OPT_APPLY_POINTMALL,$pointMallId);
			if ($tmpR['status']!=0){
				UserModel::getInstance()->rollback();
				return $tmpR;
			}

			if($tmpR['status']==0){
				self::minusStock($pointMallId);
				$exchangeLog->add($record_data);

				if($selectedWay==PointMallModel::DELIVERY_CARD) {
					$sendCard = self::finishCardExchange($uid, $pointMallItem);
					if($sendCard['status']!=0){
						UserModel::getInstance()->rollback();
						return $sendCard;
					}
					$dataSuccess['card']=$sendCard;
				}
				self::sendTemplateMsg($pointMallId,$nickname,$phone);

				$dataSuccess['stock'] = $pointMallItem['stock']==self::POINTMALL_NO_LIMIT?self::POINTMALL_NO_LIMIT:$pointMallItem['stock']-$pointMallItem['buyNum']-1;//
				$dataSuccess['buyNum'] = $pointMallItem['buyNum']+1;//已买数量
				$dataSuccess['msg'] = '兑换成功';
				$dataSuccess['ext'] = $tmpR['ext'];
				UserModel::getInstance()->commit();
				return $dataSuccess;
			}
		}
		return $dataFailure;
	}

	/**
	 * 库存减一，销量加一
	 * Author: shijy
	 * @param $pointMallId 积分商城活动编号
	 */
	public static function minusStock($pointMallId){
		self::getInstance()->where('id=' . $pointMallId)->setInc('buyNum');
	}


	/**
	 * 发送新订单模板消息
	 * @param $pointMallId
	 * @param $nickname
	 * @param $phone
	 * @param null $openID
	 */
	public static function sendTemplateMsg($pointMallId,$nickname,$phone,$openID=null){
		if (is_null($openID)){
			$openID = DEFAULT_ANSWER_OPENID;//'o9VjL1IeF2CLYVgy8GPX8iWJWZqI';
		}
		$templateId=WECHAT_TEMPLATE_POINTMALL;//'zT3H9O8Y7_8t37MecHyvNsATVgzFn9Zk-u5ji6EWPCE';
		//$storeName=self::getInstance()->where('id='.$pointMallId)->getField('titleInner');
		$url=u('PointMall/info?id='.$pointMallId);
		$templateMsg=array(
			'touser'=>$openID,
			'template_id'=>$templateId,
			'url'=>$url,
			"topcolor"=>"#FF0000",
			'data'=>array(
				"first"=>array(
					"value"=>"商城有新订单生成，请及时处理",
					"color"=>"#173177"
				),
				"keyword1"=>array(
					"value"=>$nickname,
					"color"=>"#173177"
				),
				"keyword2"=>array(
					"value"=>$phone,
					"color"=>"#173177"
				),
				"keyword3"=>array(
					"value"=>'',
					"color"=>"#173177"
				),
				"keyword4"=>array(
					"value"=>date('Y-m-d H:i:s',time()),
					"color"=>"#173177"
				),
				"remark"=>array(
					"value"=>"请尽快登陆后台进行回复",
					"color"=>"#173177"
				),

			)
		);
		$content=json_encode($templateMsg);
		WeixinModel::sendTemplateMsg($content);
	}





	/*
	 * 计算积分大转盘可抽奖次数
	 * @param $point：现有积分
	 */
	public static function getPageSet($point){
		//获取积分大转盘基数
//		$basePoint = M('lucky_prize',null,DB_MAIN_CFG)->where("prizeRank=-1 and type=".SignLuckyModel::PRIZE_TYPE_DIAL_POINT)->getField("prizeNum");
		$info = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName like 'POINT_LOTTERY_DIAL_%'")->getField('cfgName,cfgValue',true);
		$data = array(
			'dialImg'	=> '',
			'baseImg'	=> '',
			'rule'		=> '',
			'basePoint'	=> 0,
			'luckyTimes'=> 0,
		);
		foreach ($info as $key => $val){
			if($key == 'POINT_LOTTERY_DIAL_PAGE_IMG'){
				$data['baseImg'] = $val;
			} elseif ($key == 'POINT_LOTTERY_DIAL_RULE'){
				$data['rule'] = explode('$',$val);
				unset($data['rule'][count($data['rule'])-1]);
			} elseif ($key == 'POINT_LOTTERY_DIAL_BASE_POINT'){
				$data['basePoint'] = $val;
			}
		}
//		$data['dialImg'] = M('lucky_prize',null,DB_MAIN_CFG)->where("type=".SignLuckyModel::PRIZE_TYPE_DIAL_POINT." and prizeRank=-1")->getField('prizePic');
		$data['prizeInfo'] = M('lucky_prize',null,DB_MAIN_CFG)
						->where("type=".SignLuckyModel::PRIZE_TYPE_DIAL_POINT." and prizeRank >= 0")
						->field("prizeRank,prizePic")
						->select();
		if($data['basePoint'] <= 0){
			return $data;
		}
		$data['luckyTimes'] = intval($point/$data['basePoint']);
		return $data;
	}




}